package JaggSoft;

import JaggSoft.Utilidades.*;
import java.awt.*;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.TableRowSorter;

public class ReporteInventario extends javax.swing.JInternalFrame {
    private JFileChooser selector;
    public ReporteInventario() {
        initComponents();
        this.setLocation(new Point(70, 0));
        selector=new JFileChooser();
        selector.setFileFilter(new FileNameExtensionFilter("Libro de Excel",new String[]{"xls","xlsx"}));
        selector.setMultiSelectionEnabled(false);
        selector.setSelectedFile(new File("reporte_inventario.xls"));
        CargarDatos("");
    }
    private void CargarDatos(String filtro) {
        String consulta = "SELECT i.id_inventario,p.nombre,i.unidad_medida,i.detalle,i.cantidad_minima,SUM(ib.cantidad) FROM inventario i "
                + "INNER JOIN producto p ON i.id_producto=p.id_producto INNER JOIN inventario_bodega ib ON i.id_inventario=ib.id_inventario "
                + filtro + "GROUP BY i.id_inventario,p.nombre,i.unidad_medida,i.detalle,i.cantidad_minima;";
        Util.CargarTabla(jtblInventario, consulta, new String[]{"Código", "Producto", "Unidad de Medida", "Detalle", "Cantidad Mínima", "Existencia"});
        Util.AlinearColumnas(jtblInventario, SwingConstants.CENTER);
        jtblInventario.setRowSorter(new TableRowSorter<MyModeloTabla>((MyModeloTabla) jtblInventario.getModel()));
    }
    private void CargarDatosDetalle(String id){
        String consulta="SELECT (SELECT CONCAT_WS(' ',p.nombre,i.unidad_medida,i.detalle) FROM inventario i INNER JOIN producto p "
                + "ON i.id_producto=p.id_producto WHERE i.id_inventario=ib.id_inventario) AS nombre,b.nombre AS bodega,"
                + "(CASE WHEN DATE_FORMAT(ib.fecha_vencimiento,'%d/%m/%Y')='31/12/9999' THEN '-' ELSE DATE_FORMAT(ib.fecha_vencimiento,'%d/%m/%Y') "
                + "END) AS fecha_vencimiento,ib.cantidad FROM inventario_bodega ib INNER JOIN bodega b ON ib.id_bodega=b.id_bodega "
                + "WHERE ib.id_inventario="+id+";";
        Util.CargarTabla(jtblDetalleInventario,consulta,new String[]{"Producto","Bodega","Fecha de Vencimiento","Existencia"});
        Util.AlinearColumnas(jtblDetalleInventario,SwingConstants.CENTER);
        jtblDetalleInventario.setRowSorter(new TableRowSorter<MyModeloTabla>((MyModeloTabla) jtblDetalleInventario.getModel()));
    }
    private void ConsultaFiltrada(String datos[]) {
        String filtro = "";
        filtro = (!datos[0].equals("") ? " WHERE p.nombre LIKE '" + Util.ComponerTexto(datos[0]) + "%'" : "");
        filtro += (!datos[1].equals("") ? (!filtro.equals("") ? " AND" : " WHERE") + " i.unidad_medida LIKE '" + Util.ComponerTexto(datos[1]) + "%'" : "");
        filtro += (!datos[2].equals("") ? (!filtro.equals("") ? " AND" : " WHERE") + " i.detalle LIKE '" + Util.ComponerTexto(datos[2]) + "%'" : "");
        CargarDatos(filtro + " ");
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jtfNombre = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jtfUnidadMedida = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jtfDetalle = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtblInventario = new javax.swing.JTable();
        jbtnBuscar = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtblDetalleInventario = new javax.swing.JTable();
        jbtnExportar = new javax.swing.JButton();

        setClosable(true);
        setMaximizable(true);
        setTitle("Reporte de Inventario");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/reporte_inventario.png"))); // NOI18N
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentMoved(java.awt.event.ComponentEvent evt) {
                formComponentMoved(evt);
            }
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jLabel1.setText("Nombre Producto:");

        jtfNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtfNombreKeyTyped(evt);
            }
        });

        jLabel2.setText("Unidad de Medida:");

        jtfUnidadMedida.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtfUnidadMedidaKeyTyped(evt);
            }
        });

        jLabel3.setText("Detalle:");

        jtfDetalle.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtfDetalleKeyTyped(evt);
            }
        });

        jtblInventario.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtblInventarioMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jtblInventario);

        jbtnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_buscar_mini.png"))); // NOI18N
        jbtnBuscar.setToolTipText("Buscar");
        jbtnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnBuscarActionPerformed(evt);
            }
        });

        jScrollPane2.setViewportView(jtblDetalleInventario);

        jbtnExportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/excel.png"))); // NOI18N
        jbtnExportar.setToolTipText("Exportar a Excel");
        jbtnExportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnExportarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addComponent(jScrollPane2)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtfNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 109, Short.MAX_VALUE)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtfUnidadMedida, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtfDetalle)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jbtnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jtfNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(jtfUnidadMedida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel3)
                                .addComponent(jtfDetalle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jbtnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void jtfNombreKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfNombreKeyTyped
        if(!Util.SoloAlfanumericos(evt))
            evt.consume();
    }//GEN-LAST:event_jtfNombreKeyTyped
    private void jtfUnidadMedidaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfUnidadMedidaKeyTyped
        if(!Util.SoloAlfanumericos(evt))
            evt.consume();
    }//GEN-LAST:event_jtfUnidadMedidaKeyTyped
    private void jtfDetalleKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfDetalleKeyTyped
        if(!Util.SoloAlfanumericos(evt))
            evt.consume();
    }//GEN-LAST:event_jtfDetalleKeyTyped
    private void jbtnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnBuscarActionPerformed
        ConsultaFiltrada(new String[]{jtfNombre.getText(),jtfUnidadMedida.getText(),jtfDetalle.getText()});
        CargarDatosDetalle("-1");
    }//GEN-LAST:event_jbtnBuscarActionPerformed
    private void jtblInventarioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtblInventarioMouseClicked
        if(evt.getClickCount()==2 && !evt.isConsumed() && jtblInventario.getSelectedRow()>-1){
            CargarDatosDetalle(jtblInventario.getValueAt(jtblInventario.getSelectedRow(),0).toString());
        }
    }//GEN-LAST:event_jtblInventarioMouseClicked
    private void formComponentMoved(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentMoved
        if(evt.getComponent().getLocation().x<70)
            evt.getComponent().setLocation(70,evt.getComponent().getLocation().y);
        if(evt.getComponent().getLocation().y<0)
            evt.getComponent().setLocation(evt.getComponent().getLocation().x,0);
    }//GEN-LAST:event_formComponentMoved
    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        if(this.getParent().getWidth()-70<this.getWidth()  && this.isMaximum)
            this.setSize(this.getWidth()-70,this.getHeight());
    }//GEN-LAST:event_formComponentResized

    private void jbtnExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnExportarActionPerformed
        if(jtblInventario.getRowCount()>0){
            if(selector.showSaveDialog(null)==JOptionPane.OK_OPTION){
                try {
                    String ruta=selector.getSelectedFile().getAbsolutePath();
                    if(!ruta.endsWith(".xls"))
                        ruta+=".xls";
                    File archivo_excel=new File(ruta);
                    switch(Util.ExportarReporteExcel(jtblInventario,archivo_excel,"Reporte Inventario",
                            "SELECT (SELECT CONCAT_WS(' ',p.nombre,i.unidad_medida,i.detalle) FROM inventario i INNER JOIN producto p "
                            +"ON i.id_producto=p.id_producto WHERE i.id_inventario=ib.id_inventario) AS nombre,b.nombre AS bodega,"
                            +"(CASE WHEN DATE_FORMAT(ib.fecha_vencimiento,'%d/%m/%Y')='31/12/9999' THEN '-' ELSE DATE_FORMAT(ib.fecha_vencimiento,'%d/%m/%Y') "
                            +"END) AS fecha_vencimiento,ib.cantidad FROM inventario_bodega ib INNER JOIN bodega b ON ib.id_bodega=b.id_bodega "
                            +"WHERE ib.id_inventario=@id;",new String[]{"Producto","Bodega","Fecha de Vencimiento","Existencia"})){
                        case OK:
                        JOptionPane.showMessageDialog(null,"Archivo Exportado",this.getTitle(),JOptionPane.INFORMATION_MESSAGE);
                        Desktop.getDesktop().open(archivo_excel);
                        break;
                        case CANCELADO:
                        break;
                        case ERROR:
                        JOptionPane.showMessageDialog(null,"No se pudo exportar el archivo","Error",JOptionPane.ERROR_MESSAGE);
                        break;
                    }
                } catch (Exception ex) {System.err.println(ex.getMessage());}
            }
        }
        else
            JOptionPane.showMessageDialog(null,"No hay datos para exportar","Sin Datos",JOptionPane.WARNING_MESSAGE);
    }//GEN-LAST:event_jbtnExportarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jbtnBuscar;
    private javax.swing.JButton jbtnExportar;
    private javax.swing.JTable jtblDetalleInventario;
    private javax.swing.JTable jtblInventario;
    private javax.swing.JTextField jtfDetalle;
    private javax.swing.JTextField jtfNombre;
    private javax.swing.JTextField jtfUnidadMedida;
    // End of variables declaration//GEN-END:variables
}